/**
 * Copyright HCP Technology 
 * www.hcp.vn
 */
package controllers;

import java.util.List;

import play.Logger;
import play.cache.Cache;
import util.PaginationInfo;
import util.Util;
import models.ContentModel;
import models.FollowModel;

public class Follow extends Application {
	/*follow this content*/
	public static void addFollowContent(Long id){
		if(getUser() != null){
			ContentModel contentModel = Cache.get("content_" + id, ContentModel.class);
			new FollowModel(getUser(), id, contentModel.title, contentModel.alias).insert();
			List<FollowModel> followModels  = FollowModel.followContentsByUser(getUser());
			Cache.set(getKeyFollow(), followModels);
			renderText(Util.SUCCESS);
		}
	}
	/*manager list follow content*/
	public static void followContent(){
		List<FollowModel> followModels = Cache.get(getKeyFollow(), List.class);
		if(followModels == null || followModels.size() == 0){
			Logger.info("don't find cache follow user >> " + getUser());
			followModels  = FollowModel.followContentsByUser(getUser());
			Logger.info("size >>> " + followModels.size());
			if(followModels != null && followModels.size() > 0){
				Logger.info("set cache follow user >> " + getUser());
				Cache.set(getKeyFollow(), followModels);
			}	
		}
		PaginationInfo paginationInfo = new PaginationInfo();
		render(followModels, paginationInfo);
	}
	/*remove follow content by user*/
	public static void deleteFollowContent(long id){
		FollowModel.deleteFollowContent(id);
		List<FollowModel> followModels  = FollowModel.followContentsByUser(getUser());
		Cache.set(getKeyFollow(), followModels);
		renderText(Util.SUCCESS);
	}
	
	public static void checkUserFollowContent(long id){
		Logger.info("--id content is >> " + id);
		if(getUser() != null){
			List<FollowModel> followModels = Cache.get(getKeyFollow(), List.class);
			if(followModels == null || followModels.size() == 0){
				followModels  = FollowModel.followContentsByUser(getUser());
			}
			for(FollowModel follow : followModels){
				if(follow.id_content != null && follow.id_content == id){
					Logger.info("--follow.id_content content is >> " + follow.id_content);
					renderText(Util.SUCCESS);
				}
			}
			renderText(Util.FAIL);
		}
	}
		
	private static String getKeyFollow(){
		String key = "follow_" + getUser();
		return key;
	}
}
